import Cookies from 'js-cookie'

const TOKEN_KEY = 'ranxing_admin_token'
const TOKEN_EXPIRES = 7 // 7天

/**
 * 获取token
 */
export function getToken() {
  return Cookies.get(TOKEN_KEY) || localStorage.getItem(TOKEN_KEY)
}

/**
 * 设置token
 */
export function setToken(token) {
  // 同时存储在Cookie和localStorage中
  Cookies.set(TOKEN_KEY, token, { expires: TOKEN_EXPIRES })
  localStorage.setItem(TOKEN_KEY, token)
}

/**
 * 移除token
 */
export function removeToken() {
  Cookies.remove(TOKEN_KEY)
  localStorage.removeItem(TOKEN_KEY)
}

/**
 * 检查token是否存在
 */
export function hasToken() {
  return !!getToken()
}

/**
 * 解析JWT token
 */
export function parseToken(token) {
  if (!token) return null
  
  try {
    const base64Url = token.split('.')[1]
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
    const jsonPayload = decodeURIComponent(
      atob(base64)
        .split('')
        .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
        .join('')
    )
    
    return JSON.parse(jsonPayload)
  } catch (error) {
    console.error('解析token失败:', error)
    return null
  }
}

/**
 * 检查token是否过期
 */
export function isTokenExpired(token) {
  const payload = parseToken(token)
  if (!payload || !payload.exp) return true
  
  const currentTime = Math.floor(Date.now() / 1000)
  return payload.exp < currentTime
}

/**
 * 获取token剩余时间（秒）
 */
export function getTokenRemainingTime(token) {
  const payload = parseToken(token)
  if (!payload || !payload.exp) return 0
  
  const currentTime = Math.floor(Date.now() / 1000)
  return Math.max(0, payload.exp - currentTime)
}

/**
 * 格式化权限列表
 */
export function formatPermissions(permissions) {
  if (!Array.isArray(permissions)) return []
  return permissions.map(p => p.toLowerCase())
}

/**
 * 检查是否有指定权限
 */
export function hasPermission(userPermissions, requiredPermission) {
  if (!requiredPermission) return true
  if (!Array.isArray(userPermissions)) return false
  
  const formattedPermissions = formatPermissions(userPermissions)
  return formattedPermissions.includes(requiredPermission.toLowerCase())
}

/**
 * 检查是否有任一权限
 */
export function hasAnyPermission(userPermissions, requiredPermissions) {
  if (!Array.isArray(requiredPermissions) || requiredPermissions.length === 0) return true
  if (!Array.isArray(userPermissions)) return false
  
  const formattedUserPermissions = formatPermissions(userPermissions)
  const formattedRequiredPermissions = formatPermissions(requiredPermissions)
  
  return formattedRequiredPermissions.some(permission => 
    formattedUserPermissions.includes(permission)
  )
}

/**
 * 检查是否有所有权限
 */
export function hasAllPermissions(userPermissions, requiredPermissions) {
  if (!Array.isArray(requiredPermissions) || requiredPermissions.length === 0) return true
  if (!Array.isArray(userPermissions)) return false
  
  const formattedUserPermissions = formatPermissions(userPermissions)
  const formattedRequiredPermissions = formatPermissions(requiredPermissions)
  
  return formattedRequiredPermissions.every(permission => 
    formattedUserPermissions.includes(permission)
  )
}